﻿/*----------------------------------------------------------------
// 公司名称：公司名称
// 
// 产品名称：Gaf
//
// 创 建 人：netcasewqs
// 创建日期：2022/3/4
// 邮    箱：netcasewqs@qq.com
//
// Copyright (C) 2022 Gaf，保留所有权利。
//
//----------------------------------------------------------------*/
namespace Gaf.Impl;

class DelegateActivatorBase<TActivatorDescriptor> : IDelegateActivator where TActivatorDescriptor : ActivatorDescriptor
{
    internal readonly TActivatorDescriptor _activatorDescriptor;
    public object Instance { get; protected set; } = default!;

    public DelegateActivatorBase(TActivatorDescriptor activatorDescriptor, IEnumerable<Assembly> assemblies, IConfiguration? manifest)
    {
        _activatorDescriptor = activatorDescriptor;
        try
        {
            Instance = activatorDescriptor.Constructor.Invoke(assemblies, manifest);
        }
        catch (TargetInvocationException ex)
        {
            throw ex.InnerException!;
        }

        if (activatorDescriptor.SetAssembliesMethod != null)
        {
            try
            {
                activatorDescriptor.SetAssembliesMethod.Invoke(Instance, new object[] { assemblies });
            }
            catch (TargetInvocationException ex)
            {
                throw ex.InnerException!;
            }
        }
    }




    public void Configure(IServiceCollection? services, IConfiguration? configuration)
    {
        if (_activatorDescriptor.Configure == null) return;

        _activatorDescriptor.Configure.InvokdeConfigureMethod(Instance, services, configuration);
    }

    public bool Match(IServiceProvider? provider)
    {
        if (_activatorDescriptor.Match == null) return true;
        return _activatorDescriptor.Match.InvokeMatchMethod(Instance, provider);
    }

    public void Start(IServiceProvider? provider)
    {
        if (_activatorDescriptor.Start == null) return;
        _activatorDescriptor.Start.InvokeStartMethod(Instance, provider);
    }

    public void Stop(IServiceProvider? provider)
    {
        if (_activatorDescriptor.Stop == null) return;
        try
        {
            _activatorDescriptor.Stop.InvokeStartMethod(Instance, provider);
        }
        catch (TargetInvocationException ex)
        {
            throw ex.InnerException!;
        }
    }

    public void Uninstall(IServiceProvider? provider)
    {
        if (Instance is IDisposable disposable)
        {
            disposable?.Dispose();
        }

        if(Instance is IAsyncDisposable asyncDisposable)
        {
            asyncDisposable?.DisposeAsync().ConfigureAwait(false);
        }
        Instance = null!;
    }
}



